'use strict'

const Service = require('egg').Service

class PermissionsService extends Service {
  //获取用户对应的权限接口
  async getPermissionsAPI(id) {
    const { service } = this
    // 获取用户对应的角色id
    const role = await service.adminUser.getRole(id)
    const roleIds = role[0].roles.map((item) => item.id)
    // 获取角色对应的权限列表
    const perms = await service.adminUser.getPermissions(roleIds)
    const permsList = []
    perms.forEach((item) => {
      // 去清空值取出url
      const urls = item.permissions.filter((v) => v.url).map((v) => v.url)
      permsList.push(...urls)
    })

    return [...new Set(permsList)]
  }
  // 获取角色对应的权限
  getPermissions(rid) {
    const { app } = this
    return app.model.Role.findAll({
      include: [
        {
          model: app.model.Permissions,
          attributes: ['id'],
          through: {
            attributes: []
          }
        }
      ],
      attributes: [],
      where: {
        id: rid
      }
    })
  }
}

module.exports = PermissionsService
